<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author ThinkGem
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'shop:sell:shopProductSell:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="70%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <Tabs v-model:activeKey="activeKey" tabPosition="left">
      <Tabs.TabPane key="1" :forceRender="true" tab="基本信息">
        <BasicForm @register="registerForm1" />
      </Tabs.TabPane>
      <Tabs.TabPane key="2" :forceRender="true" tab="活动详情">
        <BasicForm @register="registerForm2">
          <template #remarks="{ model, field }">
            <WangEditor
              v-model:value="model[field]"
              :bizKey="record.id"
              :bizType="'shopProductSell_' + field"
              :height="500"
            />
          </template>
        </BasicForm>
      </Tabs.TabPane>
      <Tabs.TabPane key="3" :forceRender="true" tab="产品详情">
        <BasicForm @register="registerForm3">
          <template #shopProductSellInvList>
            <BasicTable
              @register="registerShopProductSellInvTable"
              @row-click="handleShopProductSellInvRowClick"
            />
            <a-button
              class="mt-2"
              @click="hanldeSelectBasInv"
              v-auth="'shop:sell:shopProductSell:edit'"
            >
              <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
            </a-button>
          </template>
        </BasicForm>
      </Tabs.TabPane>
    </Tabs>
    <ListSelect
      ref="listSelectRef"
      selectType="basInvSelect"
      :checkbox="true"
      :selectList="selectListRef"
      @select="handleSelect"
      v-show="false"
    />
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsTestTestDataForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { Tabs } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    ShopProductSell,
    shopProductSellSave,
    shopProductSellForm,
  } from '/@/api/shop/sell/shopProductSell';
  import { WangEditor } from '/@/components/WangEditor';
  import { ListSelect } from '/@/components/ListSelect';

  const emit = defineEmits(['success', 'register']);
  const listSelectRef = ref<any>(null);

  const { t } = useI18n('shop.sell.shopProductSell');
  const { showMessage } = useMessage();
  const record = ref<ShopProductSell>({} as ShopProductSell);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增活动') : t('编辑活动'),
  }));

  const activeKey = ref<string>('1');
  const selectListRef = ref<Recordable[]>([]);

  const inputFormSchemas1: FormSchema[] = [
    {
      label: t('活动标题'),
      field: 'ctitle',
      component: 'Input',
      componentProps: {
        maxlength: 200,
      },
      required: true,
    },
    {
      label: t('活动简介'),
      field: 'simpleContent',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
        rows: 5,
      },
      required: true,
    },
    {
      label: t('图片上传'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'shopProductSell_image',
        uploadType: 'image',
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('图片地址'),
      field: 'picUrl',
      component: 'Input',
      componentProps: {
        maxlength: 4000,
        disabled: true,
      },
    },
    {
      label: t('活动开始'),
      field: 'beginDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        showTime: false,
      },
      required: true,
      colProps: { lg: 12, md: 12 },
    },
    {
      label: t('活动结束'),
      field: 'endDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        showTime: false,
      },
      required: true,
      colProps: { lg: 12, md: 12 },
    },
    {
      label: t('促销包名称'),
      field: 'abbName',
      component: 'Input',
      componentProps: {
        maxlength: 200,
      },
      required: true,
    },
    {
      label: t('发布状态'),
      field: 'fbStatus',
      component: 'Select',
      componentProps: {
        dictType: 'shop_fb_status',
        allowClear: true,
      },
    },
    {
      label: t('是否关闭'),
      field: 'bclose',
      component: 'Select',
      componentProps: {
        dictType: 'sys_yes_no',
        allowClear: true,
      },
      required: true,
    },
    {
      label: t('关闭日期'),
      field: 'closeDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
    },
    {
      label: t('创建日期'),
      field: 'createDate',
      component: 'Input',
      componentProps: {
        format: 'YYYY-MM-DD',
        showTime: false,
        disabled: true,
      },
    },
  ];
  const inputFormSchemas2: FormSchema[] = [
    {
      label: t('活动详情'),
      field: 'content',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 4000,
      },
      required: true,
      slot: 'remarks',
      colProps: { lg: 24, md: 24 },
    },
  ];

  const inputFormSchemas3: FormSchema[] = [
    {
      label: t('主产品'),
      field: 'mainInv',
      fieldLabel: 'basInv.cinvname',
      component: 'ListSelect',
      componentProps: {
        selectType: 'basInvSelect',
      },
      required: true,
    },
    {
      label: t('单价'),
      field: 'fprice',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [
        { required: true },
        { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      ],
    },
    {
      label: t('起订量'),
      field: 'moq',
      component: 'Input',
      componentProps: {
        maxlength: 8,
      },
      rules: [{ required: true }, { pattern: /^\d+$/, message: t('请输入一个正整数') }],
    },
    {
      label: t('单位'),
      field: 'unitName',
      component: 'Input',
      componentProps: {
        maxlength: 8,
      },
      required: true,
    },
    {
      label: t('换算率'),
      helpMessage: '件数换算',
      field: 'ichangrate',
      component: 'Input',
      componentProps: {
        maxlength: 8,
      },
      rules: [
        { required: true },
        { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      ],
    },
    {
      label: t('副产品'),
      field: 'shopProductSellInvList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'shopProductSellInvList',
    },
  ];

  const [registerForm1, formAction1] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas1,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerForm2, formAction2] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas2,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerForm3, formAction3] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas3,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerShopProductSellInvTable, shopProductSellInvTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleShopProductSellInvDelete.bind(this, record),
          },
          auth: 'shop:sell:shopProductSell:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function resetFields() {
    activeKey.value = '1';
    await formAction1.resetFields();
    await formAction2.resetFields();
    await formAction3.resetFields();
  }

  async function setFieldsValue(values: Recordable) {
    await formAction1.setFieldsValue(values);
    await formAction2.setFieldsValue(values);
    await formAction3.setFieldsValue(values);
  }

  async function validate(): Promise<Recordable<any>> {
    return Object.assign(
      await formAction1.validate(),
      await formAction2.validate(),
      await formAction3.validate(),
    );
  }

  async function setShopProductSellInvTableData(_res: Recordable) {
    shopProductSellInvTable.setColumns([
      {
        title: t('存货编码'),
        dataIndex: 'invCode',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: true,
        required: true,
      },
      {
        title: t('存货名称'),
        dataIndex: 'basInv.cinvname',
        width: 240,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: true,
        required: true,
      },
      {
        title: t('赠送数量'),
        dataIndex: 'frate',
        width: 130,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 8,
        },
        required: true,
        editRule: true,
      },
    ]);
    shopProductSellInvTable.setTableData(record.value.shopProductSellInvList || []);
  }

  function handleShopProductSellInvRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleShopProductSellInvDelete(record: Recordable) {
    shopProductSellInvTable.deleteTableDataRecord(record);
  }

  async function getShopProductSellInvList() {
    let shopProductSellInvListValid = true;
    let shopProductSellInvList: Recordable[] = [];
    for (const record of shopProductSellInvTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        shopProductSellInvListValid = false;
      }
      shopProductSellInvList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of shopProductSellInvTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      shopProductSellInvList.push({
        ...record,
        status: '1',
      });
    }
    if (!shopProductSellInvListValid) {
      throw { errorFields: [{ name: ['shopProductSellInvList'] }] };
    }
    return shopProductSellInvList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await shopProductSellForm(data);
    record.value = (res.shopProductSell || {}) as ShopProductSell;
    setDrawerProps({ showOkBtn: record.value.bclose != '1' });
    formAction1.setProps({ disabled: record.value.bclose == '1' });
    formAction2.setProps({ disabled: record.value.bclose == '1' });
    formAction3.setProps({ disabled: record.value.bclose == '1' });
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setShopProductSellInvTableData(res);
    setDrawerProps({ loading: false });
  });

  function hanldeSelectBasInv() {
    listSelectRef.value.openSelectModal();
  }

  // 副产品
  async function handleSelect(values: Recordable[]) {
    values.forEach((item) => {
      shopProductSellInvTable.insertTableDataRecord({
        id: '',
        isNewRecord: true,
        editable: true,
        editRule: true,
        invCode: item.cinvcode,
        frate: '',
        basInv: {
          cinvname: item.cinvname,
          cinvstd: item.cinvstd,
        },
      });
    });
  }

  async function handleSubmit() {
    try {
      const data = await validate();
      console.log(data);
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.shopProductSellInvList = await getShopProductSellInvList();
      //console.log('submit', params, data, record);
      const res = await shopProductSellSave(params, data);
      showMessage(res.message);
      selectListRef.value = [];
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
